# coding: utf-8
"""
查看监控图表
"""
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
import os.path
import time
import json
import traceback
import pymongo
from get_mysql_data import get_line_item_num, SELECT_OPTIONS
from tornado.options import define, options
define("port", default=8001, help="run on the given port", type=int)


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MainHandler),
            (r"/test", IndexHandler2),
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            ui_modules={'Line': LineChartModule, 'Line_data': LineChartDataModule},
            debug=True,
        )
        # conn = pymongo.MongoClient("localhost", 27017)
        # self.db = conn["bookstore"]
        super(Application, self).__init__(handlers, **settings)
        # tornado.web.Application.__init__(self, handlers, **settings)


class IndexHandler2(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('param', 'Hell0_get')
        self.write(greeting)

    def post(self):
        # item = self.get_argument('param', 'hellO_post')
        # print type(item)
        # print len(item)
        item = dict(
            image = self.get_argument('image', 'Hell0_post'),
            price = self.get_argument('price', 'Hell0_post'),
            quan_price = self.get_argument('quan_price', 'Hell0_post'),
            quan_link = self.get_argument('quan_link', 'Hell0_post'),
            item_url = self.get_argument('item_url', 'Hell0_post'),
            item_desc = self.get_argument('item_desc', 'Hell0_post').encode('utf-8','ignore'),
            title = self.get_argument('title', 'Hell0_post').encode('utf-8','ignore')
        )
        with open ('C:/Users/you/Desktop/data.txt', 'ab') as f:
            f.write(json.dumps(item))
        # self.write(json.dumps(item))



class MainHandler(tornado.web.RequestHandler):

    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        
    def get(self):

        self.render(
            "index.html",
            page_title=u"在线观察 | 数据",
            select_options=SELECT_OPTIONS,
        )

    def post(self):
        start = self.get_argument('start', '')
        end = self.get_argument('end', '')
        option_val = self.get_argument('option_val', 'line_item_num')

        if option_val == 'line_item_num':
            datas = get_line_item_num(start, end)
            self.write(json.dumps({'data': datas}))
        else:
            self.write({})

class LineChartModule(tornado.web.UIModule):
    def render(self):
        return self.render_string('modules/line_chart.html')

class LineChartDataModule(tornado.web.UIModule):
    def render(self, datas):
        return self.render_string('modules/line_chart_js.html', datas=datas)


if __name__ == "__main__":
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


"""
main.py
"""